<template>
  <h2>当前求和为:{{ sum }}</h2>
  <button @click="sum++">点我+1</button>
  <hr />
  <h2>当前的信息为:{{ msg }}</h2>
  <button @click="msg += '!'">修改信息</button>
  <hr />
  <h2>姓名:{{ person.name }}</h2>
  <h2>年龄:{{ person.age }}</h2>
  <h2>薪资:{{ person.job.j1.salary }}K</h2>
  <button @click="person.name += '~'">修改姓名</button>
  <button @click="person.age++">修改年龄</button>
  <button @click="person.job.j1.salary++">增长薪资</button>
</template>

<script>
import { reactive, ref, watch } from "vue";
export default {
  name: "Demo",
  setup() {
    let sum = ref(0);
    let msg = ref("你好");
    let person = reactive({
      name: "张三",
      age: 18,
      job: {
        j1: {
          salary: 20,
        },
      },
    });
    //监视ref定义的一个响应式数据
    /* watch(
      sum,
      (newValue, oldValue) => {
        console.log(`新值为${newValue},旧值为${oldValue}`);
      },
      { immediate: true }
    ); */

    //监视ref定义的多个响应式数据
    /* watch(
      [sum, msg],
      (newValue, oldValue) => {
        console.log(`新值为${newValue},旧值为${oldValue}`);
      },
      { immediate: true }
    ); */

    //监视reactive定义的响应式数据
    /* watch(person, (newValue, oldValue) => {
      console.log(`新值为${JSON.stringify(newValue)},旧值为${JSON.stringify(oldValue)}`);
    }); */

    //监视reactive定义的响应式数据的某一个属性
    /* watch(
      () => person.age,
      (newValue, oldValue) => {
        console.log(`新值为${newValue},旧值为${oldValue}`);
      }
    ); */

    //监视reactive定义的响应式数据的某一些属性
    /* watch([() => person.name, () => person.age], (newValue, oldValue) => {
      console.log(`新值为${newValue},旧值为${oldValue}`);
    }); */

    //特殊情况
    watch(
      () => person.job,
      (newValue, oldValue) => {
        console.log(`新值为${JSON.stringify(newValue)},旧值为${JSON.stringify(oldValue)}`);
      },
      { deep: true }
    );
    return {
      sum,
      msg,
      person,
    };
  },
};
</script>

<style></style>
